#!/usr/bin/python
# -*- coding=utf-8 -*-
# author : fzk
# date: 20220218
# version: 0.1
import json
from jsonsearch import JsonSearch
from pandas.core.frame import DataFrame


class DoJson:
    # def __init__(self,load_dict):
    #     self.load_dict = load_dict

    def search_v(self,rp,jd):

        self.load_dict = json.loads(rp)
        li_k, li_v, li_p = [], [], []
        len_v = []
        li_lon_v,li_lon_p,li_lon_k = [], [], []
        li_long_v,li_long_p,li_long_k = [], [], []
        li_out_v,li_out_p,li_out_k,tit_p = [], [], [], []
        list_dif,li_in_v,li_in_k, li_in_p = [], [], [], []
        li_new_v,li_new_v2,li_new_v1,tit_list = [], [], [], []
        li_ind1,li_ind2,li_ind3=[], [], []
        max_l={}

        jsdata = JsonSearch(object=self.load_dict,mode='j')
        for i in jd:
            i = i.lower()
            if jsdata.search_all_value(key=i):
                li_k.append(i)
                li_v.append(jsdata.search_all_value(key=i))
                li_p.append(jsdata.search_all_path(key=i))
        li_in = [i for i,v in sorted(enumerate(li_v), key=lambda x:len(x[1]))]
        myList1 = [len(v) for i,v in sorted(enumerate(li_v), key=lambda x:len(x[1]))]
        li_long = [len(i) for i in li_v]
        #所有字段数量相等--不用处理
        if myList1[-1]== myList1[0]:
            for u,o in enumerate(li_p[li_in[-1]]):
                if type(o)==int:
                    len_v.append(li_p[li_in[-1]][:u])
                    lnd_d=u
            li_lon_p=li_p
            li_lon_k=li_k
            li_lon_v=li_v
        #找出长度最多的值
        else:
            myset=set(li_long)
            for item in myset:
                max_l[item]=li_long.count(item)
            for i,v in max_l.items():
                if v==max(max_l.values()):
                    max_i=i
            #超过或相等最多数量长度的不处理
            for i1,v1 in enumerate(li_long):
                if v1>max_i:
                    li_long_k.append(li_k[i1])
                    li_long_v.append(li_v[i1])
                    li_long_p.append(li_p[i1])
                elif v1==max_i:
                    li_out_v.append(li_v[i1])
                    li_out_k.append(li_k[i1])
                    li_out_p.append(li_p[i1])
                else:#短于一般数据
                    li_in_v.append((li_v[i1]))
                    li_in_k.append(li_k[i1])
                    li_in_p.append(li_p[i1])
            if li_out_p and li_in_p:
                for ied,yu in enumerate(li_in_p):
                    if len(yu[0]) == len(li_out_p[0][0]):
                        for tu in li_out_p[0]:
                            li_ind1.append(tu[:-2])
                        for q in yu:
                            li_ind2.append(q[:-2])
                        li_ind3.append(li_ind2)
                        # li_inn_k.append(li_in_k[ied])
                    else:#路径长于或短于一般数据的不处理
                        # li_out_k.append(li_in_k[ied])
                        li_out_v.append(li_in_v[ied])
                        li_out_p.append(yu)
                for pi,l in enumerate(li_ind3):
                    for id,now in enumerate(li_ind1):
                        if now not in l:
                            list_dif.append(id)
                    for io,v_ in enumerate(li_in_v):
                        num = 0
                        if list_dif[0] == len(v_):
                           for k in range(len(list_dif)):
                               li_new_v1.append("N/A")
                           li_new_v=v_+li_new_v1
                        else:
                            for vl in range(len(li_out_v[0])):
                                num += 1
                                if vl in list_dif:
                                    li_new_v.append("N/A")
                                    num -= 2
                                else:

                                    li_new_v.append(v_[num])
                   # li_out_k.append(li_inn_k[pi])
                    li_new_v2.append(li_new_v)
            for i in jd:
                i = i.lower()
                if jsdata.search_all_value(key=i):

                    li_lon_k.append(i)
                    li_lon_v.append(jsdata.search_all_value(key=i))
                    li_lon_p.append(jsdata.search_all_path(key=i))

            # li_lon_p = li_long_p+li_out_p+li_in_p
            # li_lon_k = li_long_k+li_out_k+li_in_k
            # li_lon_v = li_long_v+li_out_v+li_new_v2
                    # print(li_out_p)
        date_p=DataFrame(li_lon_p)
        clop=date_p.columns
        for t in clop:
            p = date_p[t].values.tolist()
            tit_p.append(p)
        data = DataFrame(li_lon_v)
        pcol= data.columns
        for p in pcol:
            d = data[p].values.tolist()
            tit_list.append(d)
        col = []
        val =[]
        resp = {}
        for i,o in enumerate(li_lon_k):
            co = {"prop": o, "label": o, "show": True}
            col.append(co)
            for y,u in enumerate(tit_list):
                if i == 0:
                    child = {}
                    if u:

                        child[o] = { "content": u[i],"path":tit_p[y][i],"show": True }
                    else:
                        child[o] = { "content": "N/A","path":"N/A","show": True }

                    val.append(child)
                else:
                    if u:

                        val[y][o] = { "content": u[i],"path":tit_p[y][i],"show": True }
                    else:
                        val[y][o] = {"content": "N/A", "path": "N/A", "show": True}



        resp["columnList"] = col
        resp["testDatas"] = val
        resp = json.dumps(resp)
        res = {}
        # res["datas"] = self.load_dict
        res["col"] = resp
        # return tit_list,tit_p,li_lon_k,self.load_dict
        return res

    def set_v(self, js, path, val):
        for i in range(len(path)):
            p = path[i]
            if i == len(path)-1:
                js[p] = val
            else:
                js = js[p]
        return js

    def mate_v(self,*args):
        pass

    def LongestWord(self,sen):
        try:
            list1 = []
            for item in sen:
                list1.append(len(item))

            list1.sort()

            if len(sen) == 0:
                return 0
            else:
                return list1[-1],list1[0]
        except Exception as e:
            print("error!")


if __name__=='__main__':
    # li = ['ED01AD01','ED01AD05','ED01AR01','ED01AD04','ED01AI02', 'ED01AD08','ED01AD02']
    LO= ["pd01ai01","pd01ad01","pd01ad03","pd01cd01","pd01aj01","pd01aj02","pd01cj01"]

    # s = pd.Series(len(li1)).sort_values(ascending=False)
    # print(s)
    rp="./pbc.json"
    try:
        with open(rp, encoding='utf-8') as load_f:

            load_dict = load_f.read()

        load_f.close()

    except Exception as e:

        raise e
    ss=DoJson().search_v(load_dict,LO)
    # # print(maxlen(len(li1)))
    print(ss)

